﻿/******************************************************************************
 * 【本类功能概述】                                 					      *
 *  版权所有（C）2017-                                           *
 *  保留所有权利。                                                            *
 ******************************************************************************
 *  作者 : <hughjk>
 *  创建时间:2019年5月21日 18:35:25
 *  文件描述:日志收集器
 *****************************************************************************/

using System;
using System.Text;
using UnityEngine;

namespace Util
{
    public class CollectLogs
    {
        private static string lastLogString;
        private static string lastLogStackTrace;
        private static LogType lastLogType;
        private static bool bIsCollcetLog;
        private static bool bIsShowStackTrace;
        private static bool bIsCaptureScreenshot;
        private static bool bIsFile;
        private static StringBuilder Sb = new StringBuilder();

        private static string CollectLogsPata { get { return PathConfig.Logs; } }

        private static string tempLog;
        private static string tineName;

        /// <summary>
        /// 初始化
        /// </summary>
        public static void Initialize(bool _bIsCollcetLog, bool _bIsShowStackTrace = true, bool _bIsCaptureScreenshot = true, bool _bIsFile = true)
        {
            bIsCollcetLog = _bIsCollcetLog;
            bIsShowStackTrace = _bIsShowStackTrace;
            bIsCaptureScreenshot = _bIsCaptureScreenshot;
            bIsFile = _bIsFile;
            lastLogString = "";
            lastLogStackTrace = "";
            Application.logMessageReceived += HandleMessage;
            Application.logMessageReceivedThreaded += HandleMessage;
            FileIO.CreateSavePath(CollectLogsPata + "/");
            AppDomain.CurrentDomain.UnhandledException += OnUncaughtExceptionHandler;
        }

        private static void OnUncaughtExceptionHandler(object sender, UnhandledExceptionEventArgs args)
        {
            Exception e = (Exception)args.ExceptionObject;
            //Console.WriteLine("MyHandler caught : " + e.Message);
            //Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
            tempLog = string.Format(" C# Error  \n Caught :{0}\n Runtime terminating: {1} \n {2}", e.Message, args.IsTerminating, args.ToString());
            debug.log(tempLog);
            tineName = TimesUtil.GetCurTime();
            Build();
        }

        private static void HandleMessage(string logString, string logStackTrace, LogType logType)
        {
            if (!bIsCollcetLog) return;
            if (string.IsNullOrEmpty(logString) && string.IsNullOrEmpty(logStackTrace)) return;
            if (lastLogString.Equals(logString) && lastLogStackTrace.Equals(logStackTrace) &&
                lastLogType == logType) return;
            lastLogString = logString;
            lastLogStackTrace = logStackTrace;
            lastLogType = logType;

            if (!bIsShowStackTrace)
            {
                logStackTrace = string.Empty;
            }
            tineName = TimesUtil.GetCurTime();
            switch (logType)
            {
                case LogType.Assert:
                    tempLog = string.Format(" Assert: {0}\nstack trace: {1}{2}\n", lastLogString, lastLogStackTrace,
                        tineName);
                    break;

                case LogType.Error:
                    tempLog = string.Format(" Error: {0}\nstack trace: {1}{2}\n", lastLogString, lastLogStackTrace,
                        tineName);

                    break;

                case LogType.Exception:
                    tempLog = string.Format(" Exception: {0}\nstack trace: {1}{2}\n", lastLogString, lastLogStackTrace,
                        tineName);
                    break;

                default:
                    tempLog = string.Format(" Default: {0}\nstack trace: {1}{2}\n", lastLogString, lastLogStackTrace,
                        tineName);
                    break;
            }

            if (logType == LogType.Error)
            {
                Build();
            }
        }

        private static void Build()
        {
            if (Sb.Length > 4)
            {
                Sb.Remove(0, 1);
            }
            Sb.Append(tempLog);
            if (bIsCaptureScreenshot)
            {   //截图保存
                CaptureScreenshot.ins.CaptureScreenshots();
            }
            if (bIsFile)
            {//保存错误日志到文件
                string txtNmae = string.Format("{0}.txt", tineName);
                string path = string.Format("{0}/{1}/", CollectLogsPata, tineName);
                FileIO.Save(path, txtNmae, GetAllLogs());
            }
        }

        public static string GetAllLogs()
        {
            return Sb.ToString();
        }
    }
}